package Demo5;


import java.lang.reflect.Parameter;

class MyBlocking{
    private int head=0;
    private int tail=0;
    private int size=0;

   private String []data;

    public MyBlocking(int capacity) {
        data=new String[capacity];
    }

    public void put(String s) throws InterruptedException {
        synchronized (this){
         while(size>= data.length){
             this.wait();
         }
            data[tail]=s;
            tail++;
            if(tail>= data.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this){
         while(size==0) {
             this.wait();
         }
         String ret=data[head];
         head++;
         if(head== data.length){
             head=0;
         }
         size--;
            this.notify();
            return ret;

        }
    }
}

public class Main12 {
    public static void main(String[] args) {
MyBlocking queue=new MyBlocking(100);
        Thread t1=new Thread(()->{
            int n=0;
while(true){
    try {
        queue.put(n+" ");
        System.out.println("生产元素:"+n);
        n++;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
        });

        Thread t2=new Thread(()->{
            while(true){
                try {
                    String s= queue.take();
                    System.out.println("消费元素"+s);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
